<template>
  <div>
    <div class="search" v-if="user.role === 'ADMIN'">
      <el-select v-model="dormId" placeholder="请选择所属宿舍">
        <el-option v-for="item in dormData" :label="item.name" :value="item.id" :key="item.id"></el-option>
      </el-select>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation" v-if="user.role === 'ADMIN'">
      <el-button type="primary" plain @click="handleAdd('手动')">手动发放</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="序号" width="80" align="center" sortable>
          <template v-slot="scope">
            {{ (pageNum - 1) * pageSize + tableData.indexOf(scope.row) + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="dormName" label="宿舍编号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="price" label="电费" show-overflow-tooltip></el-table-column>
        <el-table-column prop="power" label="用电度数"></el-table-column>
        <el-table-column prop="amount" label="缴费金额"></el-table-column>
        <el-table-column prop="time" label="缴费年月"></el-table-column>
        <el-table-column prop="status" label="缴费状态">
          <template v-slot="scope">
            <el-tag type="success" v-if="scope.row.status === '已缴费'">已缴费</el-tag>
            <el-tag type="danger" v-if="scope.row.status === '未缴费'">未缴费</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-button plain type="primary" @click="handlePay(scope.row)" size="mini" v-if="user.role === 'STUDENT' || scope.row.status === '未缴费'" :disabled="scope.row.status === '已缴费'">缴费</el-button>
            <el-button plain type="primary" @click="handleEdit(scope.row)" size="mini" v-if="user.role === 'ADMIN'">编辑</el-button>
            <el-button plain type="danger" size="mini" @click=del(scope.row.id) v-if="user.role === 'ADMIN'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog title="缴费信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
        <el-form-item prop="dormId" label="宿舍编号">
          <el-select v-model="form.dormId" placeholder="请选择所属宿舍" style="width: 100%">
            <el-option v-for="item in dormData" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="电费单价">
          <el-input price v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item prop="power" label="度数">
          <el-input price v-model="form.power" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="描述">
          <el-input type="textarea" :rows="5" v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="time" label="缴费年月">
          <el-date-picker
              v-model="form.time"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Charge",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      dormId: null,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        dormId: [
          {required: true, message: '请选择宿舍', trigger: 'change'},
        ],
        price: [
          {required: true, message: '请输入电费', trigger: 'blur'},
        ],
        time: [
          {required: true, message: '请选择缴费年月', trigger: 'blur'},
        ],
        power: [
          {required: true, message: '请输入度数', trigger: 'blur'},
        ],
      },
      ids: [],
      dormData:[]
    }
  },
  created() {
    this.load(1)
    this.$request.get('/dorm/selectAllNames').then(res=>{
      this.dormData = res.data || []
    })
  },
  methods: {
    handlePay(row){
      this.form = JSON.parse(JSON.stringify(row))
      this.$request.put('/charge/pay',this.form).then(res => {
        if (res.code === '200') {  // 表示成功保存
          this.$message.success('缴费成功')
          this.load(1)
        } else {
          this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
    },
    handleAdd(value) {   // 新增数据
      this.mode = value
      this.form = {}  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.form.mode = this.mode
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/charge/update' : '/charge/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/charge/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)   //  [1,2]
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/charge/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/charge/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          dormId: this.dormId,
        }
      }).then(res => {
        if(res.code === '200'){
          this.tableData = res.data?.list
          this.total = res.data?.total
        }else if(res.code === '505'){
          this.$message.error(res.msg);
          setTimeout(()=>{
              location.href = '/studentPerson'  // 跳转
          },2000)
        }else {
          this.$message.error(res.msg);
        }
      })
    },
    reset() {
      this.dormId = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
  }
}
</script>

<style scoped>

</style>
